﻿using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp.SystemModule;
using DevExpress.Persistent.Base;
using EasyXaf.EntityDesigner.BusinessObjects;
using EasyXaf.EntityDesigner.BusinessObjects.Entities;
using EasyXaf.EntityDesigner.BusinessObjects.Enums;
using EasyXaf.EntityDesigner.Editors.EntityAssociationEditors;
using EasyXaf.EntityDesigner.Models;

namespace EasyXaf.EntityDesigner.Controllers;

public class EntityListViewController : ObjectViewController<ListView, Entity>
{
    private NewObjectViewController _newObjectViewController;
    private ListViewProcessCurrentObjectController _listViewProcessCurrentObjectController;

    public SimpleAction EnumerationAction { get; }

    public EntityListViewController()
    {
        TargetViewNesting = Nesting.Root;

        EnumerationAction = new SimpleAction(this, "EnumerationAction", PredefinedCategory.View)
        {
            Caption = "枚举",
            ImageName = "ListBullets",
        };
    }

    protected override void OnActivated()
    {
        base.OnActivated();

        var currentDomainModelId = ((IModelCurrentDomainModel)View.Model).CurrentDomainModelId;
        if (!currentDomainModelId.HasValue)
        {
            currentDomainModelId = CurrentDomainModelUtils.Read();
            if (currentDomainModelId.HasValue)
            {
                ((IModelCurrentDomainModel)View.Model).CurrentDomainModelId = currentDomainModelId;
                View.CollectionSource.Criteria["DomainModel"] = CriteriaOperator.Parse("[EntityDesigns][[DomainModel.Oid]=?]", currentDomainModelId);
            }
            else
            {
                View.CollectionSource.Criteria["DomainModel"] = CriteriaOperator.Parse("false");
            }
        }

        _newObjectViewController = Frame.GetController<NewObjectViewController>();
        if (_newObjectViewController != null)
        {
            _newObjectViewController.NewObjectAction.Execute += NewObjectAction_Execute;
            _newObjectViewController.ObjectCreated += NewObjectViewController_ObjectCreated;
        }

        _listViewProcessCurrentObjectController = Frame.GetController<ListViewProcessCurrentObjectController>();
        if (_listViewProcessCurrentObjectController != null)
        {
            _listViewProcessCurrentObjectController.CustomizeShowViewParameters += ListViewProcessCurrentObjectController_CustomizeShowViewParameters;
        }

        EnumerationAction.Execute += EnumerationAction_Execute;
    }

    protected override void OnViewControlsCreated()
    {
        base.OnViewControlsCreated();

        if (View.Editor is EntityAssociationEditor associationEditor)
        {
            if (associationEditor.Control is EntityAssociationAdapter control)
            {
                var currentDomainModeId = ((IModelCurrentDomainModel)View.Model).CurrentDomainModelId;
                if (currentDomainModeId.HasValue)
                {
                    control.Model.DomainModelId = currentDomainModeId.Value;
                }
            }
        }
    }

    protected override void OnDeactivated()
    {
        if (_newObjectViewController != null)
        {
            _newObjectViewController.NewObjectAction.Execute -= NewObjectAction_Execute;
            _newObjectViewController.ObjectCreated -= NewObjectViewController_ObjectCreated;
        }

        if (_listViewProcessCurrentObjectController != null)
        {
            _listViewProcessCurrentObjectController.CustomizeShowViewParameters -= ListViewProcessCurrentObjectController_CustomizeShowViewParameters;
        }

        EnumerationAction.Execute -= EnumerationAction_Execute;

        base.OnDeactivated();
    }

    private void NewObjectAction_Execute(object sender, SingleChoiceActionExecuteEventArgs e)
    {
        e.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
    }

    private void NewObjectViewController_ObjectCreated(object sender, ObjectCreatedEventArgs e)
    {
        if (e.CreatedObject is Entity entity)
        {
            DomainModel domainModel = null;

            var currentDomainModeId = ((IModelCurrentDomainModel)View.Model).CurrentDomainModelId;
            if (currentDomainModeId.HasValue)
            {
                entity.DomainModel = domainModel = e.ObjectSpace.GetObjectByKey<DomainModel>(currentDomainModeId);
            }

            if (View.Editor is EntityAssociationEditor associationEditor)
            {
                if (associationEditor.Control is EntityAssociationAdapter control)
                {
                    entity.SetLocation(control.Model.ViewportBounds, domainModel);
                }
            }

            e.ObjectSpace.Committed += (_, _) =>
            {
                View.Refresh(true);
            };
        }
    }

    private void ListViewProcessCurrentObjectController_CustomizeShowViewParameters(object sender, CustomizeShowViewParametersEventArgs e)
    {
        e.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
        e.ShowViewParameters.CreatedView.ObjectSpace.Committed += DetailViewObjectSpace_Committed;
    }

    private void DetailViewObjectSpace_Committed(object sender, EventArgs e)
    {
        ObjectSpace.Refresh();
    }

    private void EnumerationAction_Execute(object sender, SimpleActionExecuteEventArgs e)
    {
        var objectSpace = Application.CreateObjectSpace(typeof(Enumeration));
        var currentDomainModelId = ((IModelCurrentDomainModel)View.Model).CurrentDomainModelId;
        var collectionSource = new CollectionSource(objectSpace, typeof(Enumeration));
        collectionSource.Criteria["DomainModel"] = new BinaryOperator("DomainModel.Oid", currentDomainModelId);
        var view = Application.CreateListView("Enumeration_Management_ListView", collectionSource, true);
        Application.ShowViewStrategy.ShowViewInPopupWindow(view);
    }
}
